<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="formData" :model="formData" :rules="rules" label-position="right"
            label-width="100px" style="width: 100%;padding-left: 20px;">
            <div class="title">基本信息</div>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="商品图片:">
                        <div class="img_view">
                            <el-upload action="anything" 
                                :http-request="(params) => uploadSectionFile1(params, 'picUpload')" 
                                :show-file-list="false" 
                                :accept="picUpload.accept.join(',')">
                                <el-image class="img" 
                                    :src="formData.image_url?formData.image_url:defaultIcon"
                                    :style="{background: (formData.image_url ? '' : '#dfdfdf')}"
                                    :fit="formData.image_url ? 'fill' : 'scale-down'"
                                ></el-image>
                            </el-upload>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商品名称:" prop="name">
                        <el-input style="width: 240px" v-model="formData.name" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商品编号:" prop="goods_no">
                        <el-input style="width: 240px" v-model="formData.goods_no" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                    <el-form-item label="条形码:">
                        <div style="display: flex;align-items: center;gap: 20px;">
                            <el-input style="width: 240px" v-model="formData.barcode" placeholder="请输入" 
                                maxlength="50" clearable></el-input>
                            <span @click="autoCreateBarcode" style="cursor: pointer;font-size: 13px;color: #0099ff;">自动生成</span>
                        </div>
                    </el-form-item>
                </el-col> -->
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="商品分类:" prop="selectCates">
                        <div style="display: flex;align-items: center;gap: 20px;">
                            <el-cascader
                                v-model="formData.selectCates"
                                :options="categorys"
                                :show-all-levels="false"
                                :props="{ checkStrictly: true, value: 'id', label: 'name' }"
                                @change='itemChanged'
                                style="width: 240px;"
                                clearable>
                            </el-cascader>
                            <span @click="showAddCateAlert=true" style="cursor: pointer;font-size: 13px;color: #0099ff;">新增分类</span>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="状态:">
                        <el-select style="width: 240px;" v-model="formData.status" placeholder="请选择" clearable>
                            <el-option label="在售" value="active"></el-option>
                            <el-option label="停售" value="inactive"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" >
                    <el-form-item label="单位:" prop="goods_unit">
                        <div style="display: flex;align-items: center;gap: 28px;">
                            <el-select style="width: 240px;" v-model="formData.goods_unit" 
                                @change="unitChange($event, 'main')" placeholder="请选择">
                                <el-option v-for="item in units" :key="'pay_'+item.id" 
                                    :label="item.name" :value="item.id"></el-option>
                            </el-select>
                            <el-checkbox v-model="formData.is_multi_unit">启用多单位</el-checkbox>
                            <span @click="showAddUnitAlert=true" style="cursor: pointer;font-size: 13px;color: #0099ff;">新增单位</span>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="formData.is_multi_unit">
                <el-col :span="20">
                    <div v-for="item in adjunctUnits" :key="'adjunct_'+item.index" class="adjunct_unit">
                        <div class="items">
                            <div class="item">
                                <span style="margin-right: 5px;">{{ '辅单位'+ item.index }}</span>
                                <el-select style="width: 240px;" v-model="item.goods_unit" placeholder="请选择"
                                     @change="unitChange($event, item.goods_unit)">
                                    <el-option v-for="item in units" :key="'pay_'+item.id" 
                                        :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </div>
                            <div class="item" v-if="item.goods_unit">
                                <span style="margin-right: 5px;">{{ '1'+ item.unit_name+' =' }}</span>
                                <el-input style="width: 240px" v-model="item.deputy_ratio" @blur="deputyRatioBlur($event, item)" 
                                    placeholder="请输入" maxlength="20" clearable>
                                     <template slot="append">{{ formData.goods_unit_name }}</template>
                                </el-input>
                            </div>
                        </div>
                        <i class="el-icon-delete" style="cursor: pointer;" @click="removeAdjunctItem(item)"></i>
                    </div>
                    <el-button style="margin: 0 0 20px 100px;" size="small" type="primary" plain 
                        v-if="adjunctUnits.length<2" icon="el-icon-plus" @click="addAdjunctItem">添加</el-button>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="规格:">
                        <el-input style="width: 240px" v-model="formData.specifications" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="型号:">
                        <el-input style="width: 240px" v-model="formData.type" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="品牌:">
                        <el-input style="width: 240px" v-model="formData.brand" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="产地:">
                        <el-input style="width: 240px" v-model="formData.origin" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="title">商品价格</div>
            <el-row>
                <el-col :span="20">
                    <div class="multi_title" v-if="formData.is_multi_unit">
                        <span>单位价格</span>
                        <div class="tags">
                            <div class="tag" v-for="item in unitArray" :key="'unit_'+item.goods_unit" :class="{select: item.select}"
                                @click="changePriceView(item)">
                                {{ item.formatterName?(item.unit_name+'('+item.formatterName+')'):item.unit_name }}</div>
                        </div>
                    </div>
                    <el-table border :data="priceTable" style="margin-top: 15px;width: 100%;">
                        <el-table-column label="单位" min-width="100" fixed align="center" prop="unit_name" />
                        <el-table-column min-width="200" fixed align="center">
                            <template slot="header" slot-scope="scope">
                                <div style="display: flex;align-items: center;flex-direction: column;gap: 3px;">
                                    <span>条形码</span>
                                    <span style="color: #0099ff;cursor: pointer;font-weight: normal;" 
                                        @click="autoCreateBarcode(scope)">自动生成</span>
                                </div>
                            </template>
                            <template slot-scope="scope">
                                <el-input style="width: 80%;margin: 0 auto;" v-model="scope.row.barcode"
                                    @blur="checkBarcodeExist($event, scope.row)" placeholder="请输入"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column align="center"
                            v-for="(col, index) in unitLevelHeaders" 
                            :key="'header_'+index"
                            :prop="col.prop" 
                            :label="col.label"
                            width="200">
                            <template slot-scope="scope">
                                <el-input style="width: 60%;margin: 0 auto;" v-model="scope.row[col.prop]"
                                    @blur="priceBlur($event, scope.row, col.prop)" placeholder="请输入"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <div class="title">商品库存</div>
            <div class="check_boxs">
                <el-checkbox v-model="formData.is_start_batch">启用批次管理</el-checkbox>
                <div class="baozhiqi">
                    <el-checkbox v-model="formData.is_start_sell_by_date" @change="saveDateChange">启用保质期管理</el-checkbox>
                    <div v-if="formData.is_start_sell_by_date" class="date">
                        <span>保质期：</span>
                        <el-input style="width: 150px;" placeholder="请输入" v-model="formData.sell_by_date_type_num">
                            <el-select style="width: 66px;color: #333;" v-model="formData.sell_by_date_type" slot="append" placeholder="请选择">
                                <el-option label="天" :value="0"></el-option>
                                <el-option label="月" :value="1"></el-option>
                                <el-option label="年" :value="2"></el-option>
                            </el-select>
                        </el-input>
                    </div>
                    <div v-if="formData.is_start_sell_by_date" class="warning">
                        <span>提前</span>
                        <el-input style="width: 100px;" v-model="formData.sell_by_date_warn_num" placeholder="请输入"></el-input>
                        <span>天预警</span>
                    </div>
                </div>
            </div>
            <el-row>
                <el-col :span="12" v-if="!isEdit">
                    <el-form-item label="初始成本:">
                        <el-input style="width: 240px" v-model="formData.init_inventory_unit_price" 
                            placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!isEdit">
                    <el-form-item label="初始库存:">
                        <el-input style="width: 240px" v-model="formData.init_inventory_quantity" @blur="stockBlur($event, 'init')"
                            @focus="stockFocus($event, 'init')" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="库存预警:">
                        <div style="display: flex;align-items: center;justify-content: space-between;width: 240px;">
                            <el-input style="width: 105px" @blur="stockBlur($event, 'low')" @focus="stockFocus($event, 'low')" 
                                v-model="formData.warn_inventory_num_low" placeholder="最低库存" maxlength="20" clearable></el-input>
                            <span>~</span>
                            <el-input style="width: 105px" @blur="stockBlur($event, 'high')" @focus="stockFocus($event, 'high')"
                                 v-model="formData.warn_inventory_num_high" placeholder="最高库存" maxlength="20" clearable></el-input>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="formData.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;margin-top: 10px;">上传附件</div>
            <el-row>
                <el-upload multiple ref="fileUpload" action="anything" :file-list="fileUploadList"
                    :http-request="(params) => uploadSectionFile(params)" :limit="5"
                    :on-preview="previewClick" :on-remove="(file) => removeFile(file)">
                    <el-button size="small" :disabled="canUpload" :class="canUpload?'btn_info_color':'btn_primary_color'" 
                        style="margin: 10px 0 0 40px;" icon="el-icon-upload2">上传附件</el-button>
                    <div slot="tip" class="el-upload__tip" style="margin-left: 20px;white-space:nowrap;display: inline-block;">
                        最多上传5个附件，单个附件大小限制在{{ max_file_size }}MB之内
                    </div>
                </el-upload>
            </el-row>
        </el-form>
        
        <bottom-btns
            Width="100%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>

        <el-dialog
            title="新增商品分类"
            :visible.sync="showAddCateAlert"
            width="32%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="cateInfo" label-width="auto" ref="cateForm" :rules="cateRules">
                    <el-form-item v-if="!showAddTopCate" label="上级分类：">
                        <el-select style="width: 240px;" v-model="cateInfo.parent_id" placeholder="请选择" clearable>
                            <el-option v-for="item in cateLists" :key="'cate_'+item.id" 
                                :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="分类名称：" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="cateInfo.name" placeholder="请输入" clearable />
                    </el-form-item>
                    <el-form-item  label="是否一级分类：">
                        <el-radio v-model="showAddTopCate" :label="true">是</el-radio>
                        <el-radio v-model="showAddTopCate" :label="false">否</el-radio>  
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showAddCateAlert=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addProductCategory">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="新增单位"
            :visible.sync="showAddUnitAlert"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="unitForm" label-width="auto" ref="unitForm" :rules="unitRules">
                    <el-form-item label="单位名称:" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="unitForm.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showAddUnitAlert=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addUnitCommit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { infoProduct, addProduct, editProduct, getProductNo, getTreeList, checkBarcode,
    getUnitList, deputyCanDelete, addTreeItem, addUnit, getPriceLevel, createBarcode } from '@/api/product';
import { uploadFiles } from '@/api/unicloudApi';
import { fileUpload } from '@/api/user';
import { baseUrl } from '@/config/env'
import { getToken } from '@/utils/auth'
import bottomBtns from "@/components/bottomBtns";

export default {
    name: 'editProduct',
    components: {
        bottomBtns
    },
    data() {
        return {
            isEdit: false,
            showAddUnitAlert: false,
            showAddTopCate: true,  //是否新增一级分类
            showAddCateAlert: false,
            backShouldRefresh: false,
            canUpload: false,
            btnCanClick: true,
            defaultIcon: 'https://anhuiyaoying.com/webs/camera.png',
            corp: '',
            pageTitle: '',
            productId: '',
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ],
            picUpload: {
                max: 5,
                accept: ['.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', '.BMP']
            },
            formData: {
                image: '',
                image_url: '',
                barcode: '',
                corp: '',
                name: '',
                goods_no: '',
                system_goods_no: '',
                selectCates: [],
                category: null,
                type: '',
                specifications: '',
                goods_unit: '',
                is_multi_unit: false,
                goods_unit_deputy: [],
                unit_retail_price: '',
                init_inventory_quantity: '0',
                init_inventory_unit_price: '0',
                warn_inventory_num_low: '0',
                warn_inventory_num_high: '0',
                unit_purchase_price: '',
                brand: '',
                origin: '',
                status: 'active',
                num: 1,
                is_start_batch: false,
                is_start_sell_by_date: false,
                sell_by_date_type: 0,   //0,'天'  1,'月'  2,'年'
                sell_by_date_type_num: '',
                sell_by_date_warn_num: '',
                file_id_list: [],
                remark: ''
            },
            rules:{
                name: [
                    { required: true, message: "请输入商品名称", trigger: 'blur' },
                ],
                selectCates: [
                    { required: true, message: "请选择商品分类", trigger: "change" },
                ],
                goods_unit: [
                    { required: true, message: "请选择单位", trigger: "change" },
                ],
                goods_no: [
                    { required: true, message: "请输入商品编号", trigger: "blur" },
                ]
            },
            cateInfo: {
                name: '',
                parent_id: null,
                description: '',
                corp: ''
            },
            cateRules:{
                name: [
                    { required: true, message: "请输入分类名称", trigger: "blur" },
                ],
            },
            unitForm: {
                name: '',
                corp: ''
            },
            unitRules:{
                name: [
                    { required: true, message: "请输入单位名称", trigger: "blur" },
                ],
            },
            units: [],
            adjunctUnits: [],  //辅单位
            selectUnitId: '',
            categorys: [],
            priceTable: [],
            cateLists: [],
            unitArray: [],
            unitLevelHeaders: [],
            fileUploadList: [],
            max_file_size: 10,  //最大可上传文件大小（MB）
            priceLevelItem: {}
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        },
    },
    watch: {
        'formData.is_multi_unit': function(val) {
            if (val && !this.formData.goods_unit) {
                this.$message.error('请先选择主单位')
                this.formData.is_multi_unit = false
                return
            }
            if (val && !this.adjunctUnits.length) {
                this.adjunctUnits = [{
                    index: 1,
                    unit_name: '',
                    goods_unit: '',
                    deputy_ratio: 0,
                    barcode: '',
                    is_main: false
                }]
            }
            if (!val) {
                this.adjunctUnits = []
            }
        }
    },
    mounted() {
        this.corp = this.corpId
        this.formData.corp = this.corp
        this.productId = this.editId
        this.getUnits()
        this.getUnitLevels()
        this.getProductCategory()
    },
    methods: {
        goBack() {
            this.$emit('hidden', {isRefresh: this.backShouldRefresh})
        },
        stockFocus(val, type) {
            let value = val.target.value
            if (value && parseFloat(value)===0){
                if (type == 'init'){
                    this.formData.init_inventory_quantity = ''
                }else if (type == 'low'){
                    this.formData.warn_inventory_num_low = ''
                }else if (type == 'high'){
                    this.formData.warn_inventory_num_high = ''
                }
            }
        },
        stockBlur(val, type) {
            let value = val.target.value
            value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }

            if (type == 'low'){
                this.formData.warn_inventory_num_low = value ? parseFloat(value) : 0
            }else if (type == 'high'){
                this.formData.warn_inventory_num_high = value ? parseFloat(value) : 0
            }else if (type == 'init'){
                this.formData.init_inventory_quantity = value ? parseFloat(value) : 0
            }

            // 校验合法
            const min = parseFloat(this.formData.warn_inventory_num_low) || 0
            const max = parseFloat(this.formData.warn_inventory_num_high) || 0

            if (min > max){
                this.formData.warn_inventory_num_low = max
            }
        },
        // 商品详情
        getProductInfo() {
            infoProduct(this.productId, {corp: this.formData.corp}).then(res => {
                let info = res.data.data
                info.image_url = info.image ? info.image_show.url : ''
                info.selectCates = [info.category]
                if (info.category_detail && JSON.stringify(info.category_detail.parent)!='{}'){
                    info.selectCates = [ info.category_detail.parent.id, info.category]
                }
                info.unit_retail_price = info.unit_retail_price?parseFloat(info.unit_retail_price):''
                info.unit_purchase_price = info.unit_purchase_price?parseFloat(info.unit_purchase_price):''
                this.formData = info

                this.adjunctUnits = []
                let unitName = info.unit_show ? info.unit_show.name : ''
                this.formData.goods_unit_name = unitName
                if (info.deputy_show && info.deputy_show.length) {
                    this.adjunctUnits = info.deputy_show.filter((item, index) => {
                        item.index = index+1
                        item.formatterName = '1'+item.unit_name+'='+parseFloat(item.deputy_ratio)+unitName
                        return item
                    })
                }
                let mainUnitItem = info.unit_deputy_show.find(el => el.is_main)
                let array = [mainUnitItem].concat(this.adjunctUnits)
                this.unitArray = array.filter((item, index) => {
                    item.select = false
                    if (index === 0) {
                        item.select = true
                        this.priceTable = [item]
                    }
                    return item
                })

                // 附件
                if (info.file_list_show && info.file_list_show.length){
                    this.formData.file_id_list = info.file_list_show.map(item => item.id)
                    this.fileUploadList = info.file_list_show.filter(item => {
                        item.url = item.url_show
                        item.name = item.file_name
                        return item
                    })
                }else{
                    this.formData.file_id_list = []
                }
            })
        },
        // 自动生成商品编号
        getGoodsNumber() {
            getProductNo({corp_id: this.corp}).then(res => {
                this.formData.goods_no = res.data.data.system_goods_no
                this.formData.system_goods_no = res.data.data.system_goods_no
            })
        },
        // 自动生成商品条形码 
        autoCreateBarcode(row) {
            createBarcode({
                get_num: 1,
                corp_id: this.corp
            }).then(res => {
                let code = res.data.data.barcode_list[0]
                this.priceTable[0].barcode = code
            })
        },
        checkBarcodeExist(val, row) {
            let code = val.target.value
            if (!code) return
            
            checkBarcode({
                barcode: code,
                corp_id: this.corp
            }).then(res => {
                if (res.data.data.is_exists){
                    this.$message.error('商品条形码【'+code+'】已存在')
                }
            })
        },
        // 获取商品分类
        getProductCategory() {
            let that = this
            getTreeList({corp: this.corp}).then(res => {
                let categorys = res.data.data.category_list.filter(item => { return !item.parent })
                that.categorys = categorys

                that.cateLists = []
                res.data.data.category_list.forEach(item => {
                    if (!item.parent){
                        that.cateLists.push(item)
                    }
                })
                
                if (that.productId) {
                    that.pageTitle = '编辑商品'
                    that.isEdit = true
                    that.getProductInfo()
                }else{
                    that.pageTitle = '新增商品'
                    that.isEdit = false
                    that.getGoodsNumber()
                }
            })
        },
        addProductCategory() {
            var that = this
            that.$refs['cateForm'].validate(valid => {
                if(!valid) return
                
                that.cateInfo.corp = that.formData.corp
                addTreeItem(that.cateInfo).then(res => {
                    if (res.code == 200){
                        that.cateInfo.name = ''
                        that.cateInfo.parent_id = null
                        that.getProductCategory()
                        that.showAddCateAlert = false
                        that.backShouldRefresh = true
                        that.$message({
                            message: '新增成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        // 获取单位
        getUnits() {
            getUnitList({corp: this.corp}).then(res => {
                this.units = res.data.data.unit_list
            })
        },
        // 获取单位等级
        getUnitLevels() {
            getPriceLevel({corp: this.corp, is_start: 1}).then(res => {
                let cell = {
                    goods_unit: '',
                    unit_name: '',
                    deputy_ratio: 0,
                    barcode: '',
                    is_main: true
                }
                this.priceLevelItem = {}
                this.unitLevelHeaders = res.data.data.level_list.filter((item, index) => {
                    item.label = item.price_name
                    item.prop = item.price_column_name
                    this.$set(cell, item.price_column_name, '')
                    this.$set(this.priceLevelItem, item.price_column_name, '')
                    return item
                })
                this.priceTable = [cell]
            })
        },
        addUnitCommit() {
            var that = this
            that.$refs['unitForm'].validate(valid => {
                if(!valid) return

                that.unitForm.corp = that.formData.corp
                addUnit(that.unitForm).then(res => {
                    if (res.code == 200){
                        that.unitForm.name = ''
                        that.getUnits()
                        that.showAddUnitAlert = false
                        that.$message({
                            message: '新增成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        unitChange(val, type) {
            let name = ''
            const item = this.units.find(item => item.id===val)
            name = item ? item.name : ''
            
            if (type == 'main') {
                this.formData.goods_unit_name = name
                this.priceTable.forEach(_item => {
                    _item.goods_unit = val
                    _item.unit_name = name
                    _item.deputy_ratio = 0
                    _item.is_main = true
                })
                this.unitArray = this.priceTable
            }else{
                let flag = false
                if (type == this.formData.goods_unit){
                    this.adjunctUnits.forEach(_item => {
                        if (_item.goods_unit === type) {
                            _item.unit_name = ''
                            _item.goods_unit = ''
                        }
                    })
                    flag = true
                }else{
                    for (let index = 0; index < this.adjunctUnits.length-1; index++) {
                        const element = this.adjunctUnits[index];
                        if (element.goods_unit == type){
                            flag = true
                            break
                        }
                    }
                    if (flag){
                        this.adjunctUnits[this.adjunctUnits.length-1].unit_name = ''
                        this.adjunctUnits[this.adjunctUnits.length-1].goods_unit = ''
                    }
                }
                if (flag){
                    this.$message.error('当前单位已存在，请重新选择')
                    return
                }
                this.adjunctUnits.forEach(_item => {
                    if (_item.goods_unit === type) {
                        _item.unit_name = name
                    }
                })
                this.getUnitArray()
            }
        },
        addAdjunctItem() {
            let flag = false
            if (this.adjunctUnits.length){
                for (var i = 0; i < this.adjunctUnits.length; i++) {
                    let item = this.adjunctUnits[i]
                    if (!item.goods_unit){
                        flag = true
                        break;
                    }
                }
            }
            if (flag){
                this.$message.error('请选择辅单位')
                return
            }
            
            this.adjunctUnits.push({
                index: this.adjunctUnits.length+1,
                unit_name: '',
                goods_unit: '',
                deputy_ratio: 0,
                barcode: '',
                is_main: false
            })
        },
        deputyRatioBlur(val, item) {
            let value = val.target.value
            value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            console.log(value)

            this.unitArray.forEach(_item => {
                if (_item.goods_unit === item.goods_unit){
                    _item.deputy_ratio = value
                    _item.formatterName = '1'+_item.unit_name+'='+_item.deputy_ratio+this.formData.goods_unit_name
                    item.formatterName = _item.formatterName
                }
            })
            this.$forceUpdate()
        },
        saveDateChange(val) {
            if (!val){
                this.formData.sell_by_date_type_num = ''
                this.formData.sell_by_date_warn_num = ''
                this.formData.sell_by_date_type = 0
            }
        },
        priceBlur(val, row, type) {
            let value = val.target.value
            value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            console.log(value, row, type)
            
            this.unitArray.forEach(item => {
                if (item.goods_unit === row.goods_unit){
                    if (type == 'sale'){
                        item.unit_retail_price = value
                    }else if(type == 'buy'){
                        item.unit_purchase_price = value
                    }
                }
            })
            this.$forceUpdate()
        },
        removeAdjunctItem(item) {
            if (this.isEdit){
                // 先判断是否可删
                deputyCanDelete({
                    corp: this.formData.corp,
                    goods_id: item.goods,
                    deputy_unit_id: item.goods_unit
                }).then(res => {
                    if (res.data.msg == '可以删除'){
                        let _res = this.adjunctUnits.filter(_item => _item.index!=item.index)
                        this.adjunctUnits = _res.filter((_item, _index) => {
                            _item.index = _index+1
                            return _item
                        })
                        this.selectUnitId = ''
                        this.getUnitArray()
                    }else{
                        this.$message.error(res.msg)
                    }
                })
            }else{
                let res = this.adjunctUnits.filter(_item => _item.index!=item.index)
                this.adjunctUnits = res.filter((_item, _index) => {
                    _item.index = _index+1
                    return _item
                })
                this.selectUnitId = ''
                this.getUnitArray()
            }
            
            if (!this.adjunctUnits.length){
                this.formData.is_multi_unit = false
            }
        },
        changePriceView(item) {
            let mainItem = this.unitArray.find(_item => _item.is_main)
            let that = this
            this.unitArray.forEach(_item => {
                _item.select = false
                if (_item.goods_unit === item.goods_unit){
                    _item.select = true
                    // _item = Object.assign({}, _item, this.priceLevelItem)
                    if (!_item.is_main){
                        for (let key in that.priceLevelItem) {
                            if (!_item.hasOwnProperty(key)) {
                                that.$set(_item, key, '')
                            }
                            let value = _item[key];
                            if (!value && mainItem[key]){
                                let price = that.$common.multiplyFloat(parseFloat(mainItem[key]), parseFloat(_item.deputy_ratio)) 
                                that.$set(_item, key, price)
                            }
                        }  
                    }
                    this.selectUnitId = item.goods_unit
                    this.priceTable = [_item]
                }
            })
            this.$forceUpdate()
        },
        getUnitArray() {
            if (this.formData.is_multi_unit){
                this.adjunctUnits.forEach(item => {
                    item.formatterName = '1'+item.unit_name+'='+item.deputy_ratio+this.formData.goods_unit_name
                })
                let array = this.priceTable.concat(this.adjunctUnits)
                this.unitArray = array.filter((item, index) => {
                    item.select = false
                    if (!this.selectUnitId){
                        item.select = index===0
                    }else if (item.goods_unit === this.selectUnitId){
                        item.select = true
                    }
                    if (item.select){
                        this.priceTable = [item]
                    }
                    return item
                })
            }
            this.$forceUpdate()
        },
        // 分类点击
        itemChanged(val) {
            if (val && val.length>0){
                this.formData.category = val[val.length-1]
            }else{
                this.formData.category = null
            }
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            that.$refs['formData'].validate(valid => {
                if(!valid) return

                if (!that.btnCanClick) return

                that.btnCanClick = false
                let params = that.formData
                delete params['selectCates']

                function cleanEmptyFields(obj) {
                    Object.keys(obj).forEach(key => {
                        if (typeof obj[key] === 'object' && obj[key] !== null) {
                            cleanEmptyFields(obj[key]); // 递归处理嵌套对象
                        } else if (obj[key] === '' || obj[key] === undefined) {
                            obj[key] = null;
                        }
                    });
                }

                params.goods_unit_deputy = []
                that.unitArray.forEach(item => {
                    item.is_main = false
                    if (params.goods_unit === item.goods_unit) { //主单位
                        // params.unit_retail_price = item.unit_retail_price
                        // params.unit_purchase_price = item.unit_purchase_price
                        item.is_main = true
                    }
                    cleanEmptyFields(item);
                    params.goods_unit_deputy.push(item)
                })

                if (!that.formData.is_start_sell_by_date){
                    that.formData.sell_by_date_type_num = 0
                    that.formData.sell_by_date_warn_num = 0
                }else{
                    that.formData.sell_by_date_type_num = parseFloat(that.formData.sell_by_date_type_num)
                    that.formData.sell_by_date_warn_num = parseFloat(that.formData.sell_by_date_warn_num)
                }

                let temp = null
                if (that.productId) {
                    delete params['supplier']
                    temp = editProduct(that.productId, params)
                }else{
                    temp = addProduct(params)
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        that.btnCanClick = true
                        that.$emit('success')
                    }
                })
            })
        },
        // ----------------- 图片上传 -------------------
        // 上传前校验
        beforeUpload1 (file, uploadType) {
            let isRightSize = file.size / 1024 / 1024 < this[uploadType].max
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this[uploadType].max + 'MB')
            }
            let fileArr = file.name.split('.')
            let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + fileArr[fileArr.length - 1])
            if (!isAccept) {
                this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            }
            return isRightSize && isAccept
        },
        // 附件上传
        uploadSectionFile1 (params, uploadType) {
            let _this = this
            if (!this.beforeUpload1(params.file, uploadType)) {
                params.onError()
                return
            }
            
            let name = params.file.name.split('.')
            let file_ext = name[name.length-1]
            const reader = new FileReader();
            // 定义读取完成后的处理逻辑
            reader.onload = (e) => {
                // e.target.result 是文件的内容，这里是 ArrayBuffer
                const arrayBuffer = e.target.result;
                const buffer = Buffer.from(arrayBuffer); // 转换为 Buffer

                // 将 Buffer 转换为 Base64 字符串
                const path = buffer.toString('base64');

                uploadFiles({ file_ext, path }).then(res => {
                    _this.formData.image_url = res.data.fileID
                    // 调用我们的上传接口,获取image_id
                    fileUpload({
                        fileId: res.data.fileID,
                        requestId: '',
                        url: res.data.fileID,
                        corp_id: _this.corp
                    }).then(res => {
                        _this.formData.image = res.data.id || ''
                    })
                })
                // 这里可以进行其他操作，比如展示或上传 blob
            };
            // 定义读取错误后的处理逻辑
            reader.onerror = (error) => {
                console.error('File reading error:', error);
            };
            // 读取文件内容为 ArrayBuffer
            reader.readAsArrayBuffer(params.file);
        },
        // ===================== 附件上传相关 ===========================
        // 上传前校验
        beforeUpload (file) {
            let isRightSize = file.size / 1024 / 1024 < this.max_file_size
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this.max_file_size + 'MB')
            }
            // let fileArr = file.name.split('.')
            // let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + fileArr[fileArr.length - 1])
            // if (!isAccept) {
            //     this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            // }
            return isRightSize
        },
        // 自定义附件上传
        uploadSectionFile (params) {
            let _this = this
            if (!this.beforeUpload(params.file)) {
                params.onError()
                return
            }
            if (this.canUpload) return
             const loading = this.$loading({
                lock: true,
                text: '正在上传附件中，请稍后...'
            });
            _this.canUpload = true
            const formdata = new FormData()
            formdata.append('up_file', params.file)
            formdata.append('file_name', params.file.name)
            var xhr = new XMLHttpRequest();
            xhr.open("POST", baseUrl+'/upload_file/ali_oss_priv', true); //链接改成你项目中的
            xhr.setRequestHeader("TOKEN", getToken());  //令牌改成你项目中的
            xhr.setRequestHeader("CORP-ID", this.corp);  //令牌改成你项目中的
            xhr.send(formdata);
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var obj = JSON.parse(xhr.responseText); //返回值
                    _this.formData.file_id_list.push(obj.data.id)
                    _this.fileUploadList.push({
                        name: obj.data.file_name,
                        url: obj.data.url_show,
                        id: obj.data.id
                    })
                    _this.$message.success('上传成功')
                    _this.canUpload = false
                    loading.close();
                }
            }
        },
        previewClick(file) {
            location.href = file.url
        },
        removeFile(file) {
            this.fileUploadList = this.fileUploadList.filter(item => item.id !== file.id)
            this.formData.file_id_list = this.formData.file_id_list.filter(item => item !== file.id)
        }
    }
}
</script>

<style lang="less" scoped>
	@import '../../style/mixin';
    .title {
        width: 100%;
        padding: 10px 0 20px 0;
        font-size: 15px;
        font-weight: bold;
    }
    .check_boxs {
        display: flex;
        justify-content: start;
        flex-direction: column;
        gap: 20px;
        padding-left: 50px;
        padding-bottom: 20px;
        .baozhiqi {
            display: flex;
            align-items: center;
            .date {
                display: inline-flex;
                align-items: center;
                margin-left: 50px;
                font-size: 14px;
                gap: 5px;
                width: 260px;
            }
            .warning {
                display: inline-flex;
                align-items: center;
                margin-left: 50px;
                font-size: 14px;
                gap: 5px;
            }
        }
    }
    .adjunct_unit {
        display: flex;
        height: 80px;
        align-items: center;
        justify-content: space-between;
        background: #fcfcfc;
        border: 1px solid #e8e8e8;
        border-radius: 2px;
        margin-left: 100px;
        margin-bottom: 10px;
        padding: 0 20px;
        .items {
            display: flex;
            align-items: center;
            gap: 20px;
            .item {
                font-size: 14px;
            }
        }
    }
    .multi_title {
        margin-left: 44px;
        padding-bottom: 10px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 20px;
        .tags {
            display: flex;
            align-items: center;
            gap: 20px;
            .tag {
                background-color: #d8ffff;
		        color: #333;
                padding: 0 20px;
                height: 30px;
                line-height: 30px;
		        border-radius: 15px;
                cursor: pointer;
            }
            .select {
                background-color: #0099ff;
                color: #fff;
            }
        }
    }
    .img_view {
        display: flex;
        align-items: center;
        height: 100px;
        padding-left: 10px;
        .img {
            width: 100px;
            height: 100px;
            &:hover{
                cursor: pointer;
            }
        }
    }
</style>

<style>
.el-table__body-wrapper {
  overflow-x: auto !important;
}
/* 自定义滚动条样式（Webkit） */
.el-table__body-wrapper::-webkit-scrollbar {
  height: 8px;
}
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}
.el-upload-list__item {
    margin-left: 36px !important;
    width: calc(100% - 36px) !important;
}
</style>